package com.team.bus.module.menu.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjframework.traceframe.common.controller.BaseController;
import org.zjframework.traceframe.common.dao.util.ConfigUtil;
import org.zjframework.traceframe.common.dao.util.StringUtil;
import org.zjframework.traceframe.common.pagemodel.Tree;
import org.zjframework.traceframe.common.util.JSONUtil;
import org.zjframework.traceframe.common.util.PageHelper;
import com.team.bus.module.common.pagemodel.SessionInfo;
import com.team.bus.module.menu.model.Menu;
import com.team.bus.module.menu.service.IMenuService;
import com.team.bus.module.role.model.Role;
import com.team.bus.module.user.model.User;

@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {

	@Autowired
	private IMenuService menuService;

	/**
	 * @author 赵继
	 * @return
	 * 功能描述：跳转到栏目页列表页
	 */
	@RequestMapping("/menu")
	public String show(){
		return "menu/menu";
	}

	@RequestMapping(value = "/getTreeMenu")
	public void getTreeMenu(String id,HttpServletRequest request,HttpServletResponse response) {
		List<Menu> menus = new ArrayList<Menu>();
		List<com.team.bus.module.menu.pagemodel.Menu> pmenus = new ArrayList<com.team.bus.module.menu.pagemodel.Menu>();
		if(id==null || id.equals("")){
			menus = menuService.findHql("from Menu where menu is null order by orderno");
		}else{
			menus = menuService.findHql("from Menu where menu.id=? order by orderno",id);
		}
		for(Menu m : menus){
			com.team.bus.module.menu.pagemodel.Menu pm = new com.team.bus.module.menu.pagemodel.Menu();
			BeanUtils.copyProperties(m, pm);
			Map<String,Object> attributes = new HashMap<>();
			attributes.put("url", m.getUrl());
			pm.setAttributes(attributes);
			if(m.getMenus()!=null && !m.getMenus().isEmpty()){
				pm.setState("closed");
			}else{
				pm.setState("open");
			}
			pmenus.add(pm);
		}
		super.writeJSON(pmenus,request,response);
	}

	@RequestMapping(value = "/getTree")
	@ResponseBody
	public List<Tree> getTree(SessionInfo sessionInfo,HttpSession session) {
		sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		List<Menu> menus = new ArrayList<Menu>();
		List<Tree> lt = new ArrayList<Tree>();
		if(sessionInfo!=null){
			Map<String,Object> param = new HashMap<>();
			param.put("userId", sessionInfo.getId());
			menus = menuService.findHql("select distinct m from Menu m join fetch m.roles roles join roles.users user where user.id=:userId order by m.orderno",param);
		}else{
			menus = menuService.findHql("from Menu order by orderno");
		}
		if(menus!=null){
			for(Menu m : menus){
				Tree tree = new Tree();
				BeanUtils.copyProperties(m, tree);
				Map<String,Object> attributes = new HashMap<>();
				attributes.put("url", m.getUrl());
				tree.setAttributes(attributes);
				if(m.getMenu()!=null){
					tree.setPid(m.getMenu().getId());
				}

				lt.add(tree);
			}
		}
		return lt;
	}

	/**
	 * @author 赵继
	 * @return
	 * 功能描述：异步加载TreeGrid
	 */
	@RequestMapping("/treegrid")
	public void treegrid(HttpServletRequest request,HttpServletResponse response,PageHelper ph,String id){
		String hql = "";
		Map<String,Object> param = new HashMap<>();
		hql = "from Menu order by orderno";
		List<Menu> smenus = menuService.findHql(hql, param);
		List<com.team.bus.module.menu.pagemodel.Menu> tmenus = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Menu s : smenus){
			com.team.bus.module.menu.pagemodel.Menu m = new com.team.bus.module.menu.pagemodel.Menu();
			BeanUtils.copyProperties(s, m);

			if(s.getMenu()!=null){
				m.setPid(s.getMenu().getId());
			}
			if(s.getUrl()!=null){
				attributes.put("url", s.getUrl());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
			m.setAttributes(attributes);
			tmenus.add(m);
		}
		super.writeJSON(tmenus, request, response);
	}


	@RequestMapping("/tree")
	@ResponseBody
	public List<com.team.bus.module.menu.pagemodel.Menu> tree() {
		String hql = "";
		Map<String,Object> param = new HashMap<>();
		hql = "from Menu order by orderno";
		List<Menu> smenus = menuService.findHql(hql, param);
		List<com.team.bus.module.menu.pagemodel.Menu> tmenus = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Menu s : smenus){
			com.team.bus.module.menu.pagemodel.Menu t = new com.team.bus.module.menu.pagemodel.Menu();
			BeanUtils.copyProperties(s, t);

			if(s.getMenu()!=null){
				t.setPid(s.getMenu().getId());
			}
			if(s.getUrl()!=null){
				attributes.put("url", s.getUrl());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
			t.setAttributes(attributes);
			tmenus.add(t);
		}
		return tmenus;
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/addTo")
	public String addTo(){

		return "/menu/menuAdd";
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/editTo")
	public String editTo(){

		return "/menu/menuEdit";
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/edit")
	public void edit(HttpServletRequest request,HttpServletResponse response,
					 com.team.bus.module.menu.pagemodel.Menu pmenu){
		JSONUtil json = new JSONUtil();
		Menu menu = new Menu();
		try {
			if(pmenu!=null){
				BeanUtils.copyProperties(pmenu, menu);
				Menu tmenu1=new Menu();
				if(StringUtil.isNotEmpty(pmenu.getPid())) {
					tmenu1 = menuService.get(Menu.class, pmenu.getPid());
				}
				String famenuid = tmenu1.getId();

				menuService.executeSql("update tmenu set pid=?,text=?,url=?,orderno=?,iconcls=?,sstyle=? where id=?", famenuid, pmenu.getText(), pmenu.getUrl(), pmenu.getOrderno(),pmenu.getIconcls(),pmenu.getSstyle(), pmenu.getId());
				json.setSuccess(true);
				json.setMsg("编辑成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.setSuccess(false);
			json.setMsg(e.getMessage());
		}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/edit11")
	public void edit1(HttpServletRequest request,HttpServletResponse response,
					  com.team.bus.module.menu.pagemodel.Menu pmenu){

		JSONUtil json = new JSONUtil();
		Menu menu = new Menu();
		try {
			if(pmenu!=null){
				BeanUtils.copyProperties(pmenu, menu);
				Menu tmenu1 = menuService.get(Menu.class, pmenu.getPid());
				menu.setMenu(tmenu1);
				menu.setMenus(new HashSet<Menu>());
				menu = menuService.updateRow(menu);
				json.setSuccess(true);
				pmenu.setId(pmenu.getId());
				if(menu.getMenu().getId()!=null){
					pmenu.setPid(menu.getMenu().getId());
				}
				json.setObj(pmenu);
				json.setMsg("编辑成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg(e.getMessage());
		}
		super.writeJSON(json,request,response);
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/save")
	public void save(HttpServletRequest request,HttpServletResponse response,
					 com.team.bus.module.menu.pagemodel.Menu pmenu){

		JSONUtil json = new JSONUtil();
		Menu menu = new Menu();
		try {
			if(pmenu!=null){
				BeanUtils.copyProperties(pmenu, menu);
				Menu tmenu1 = new Menu();
				if(!StringUtil.isEmpty(pmenu.getPid())){
					tmenu1  = menuService.get(Menu.class, pmenu.getPid());
					menu.setMenu(tmenu1);
				}
				menu.setRoles(new HashSet<Role>());
				menu = menuService.saveInsertRow(menu);
				json.setSuccess(true);
				json.setMsg("操作成功");
				pmenu.setId(menu.getId());
				if(StringUtil.isNotEmpty(menu.getMenu())){
					if(!menu.getMenu().getId().equals("")){
						pmenu.setPid(menu.getMenu().getId());
					}
				}
				json.setObj(pmenu);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg(e.getMessage());
		}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/del")
	public void delete(HttpServletRequest request,HttpServletResponse response,String ids){

		JSONUtil json = new JSONUtil();
		StringBuffer hql = new StringBuffer();
		hql.append("delete Menu where id=");
		hql.append("'"+ids+"'");
		try {
			menuService.executeHql(hql.toString());
			json.setSuccess(true);
			json.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("删除失败:"+e.getMessage());
		}
		super.writeJSON(json,request,response);

	}


	@RequestMapping(value = "/getMenulist")
	@ResponseBody
	public List<com.team.bus.module.menu.pagemodel.Menu> getMenulist(HttpSession session) {
		List<Menu> menus = new ArrayList<Menu>();
		User user = (User)session.getAttribute("user");
		String hql = "";
		if("系统管理员".equals(user.getRolename().trim())){
			hql = "from Menu order by orderno";
		}else{
			hql = "select distinct m from Menu m join fetch m.roles roles join roles.users user where user.id=:userId order by m.orderno";
		}
		List<com.team.bus.module.menu.pagemodel.Menu> lt = new ArrayList<com.team.bus.module.menu.pagemodel.Menu>();
		Map<String,Object> param = new HashMap<>();
		if(!"系统管理员".equals(user.getRolename().trim())){
			param.put("userId", ((User)session.getAttribute("user")).getId());
			menus = menuService.findHql(hql,param);
		}else{
			menus = menuService.findHql(hql);
		}

		if(menus!=null){
			for(Menu m : menus){
				com.team.bus.module.menu.pagemodel.Menu tree = new com.team.bus.module.menu.pagemodel.Menu();
				BeanUtils.copyProperties(m, tree);
				lt.add(tree);
			}
		}
		return lt;
	}







}
